<template>
  <div>
    <el-collapse-transition>
      <div class="main">
        <el-upload
          v-show="!isShowProgress"
          action="#"
          list-type="picture-card"
          :file-list="fileList"
          :on-remove="handleRemove"
          :http-request="handleRequest"
          :class="{display:fileList.length}"
          :on-change="onchange"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          accept="image/gif, image/jpeg,image/png"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
      </div>
    </el-collapse-transition>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// id: AKIDc2C6j5C2cv0oLccMp1xc07yZtwiDSQ7X
// key : C7l8F6gz1mGTP5UGm1zg6F8j36tPecJk
const cos = new COS({
  SecretId: 'AKIDc2C6j5C2cv0oLccMp1xc07yZtwiDSQ7X',
  SecretKey: 'C7l8F6gz1mGTP5UGm1zg6F8j36tPecJk'
})
export default {
  name: 'UploadImage',
  props: {
    defaultUrl: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      currentUid: '',
      percentage: 0,
      isShowProgress: false
    }
  },
  watch: {
    defaultUrl: {
      immediate: true,
      handler(val) {
        if (val) {
          this.fileList = [{
            url: val
          }]
        }
      }
    }
  },
  created() {

  },
  methods: {
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handleRequest({ file }) {
      cos.putObject({
        Bucket: 'hrsass-file-1307760742', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: (progressData) => {
          this.isShowProgress = true
          this.percentage = progressData.percent * 100
          this.timer = setInterval(() => {
            if (this.percentage >= 99) {
              clearInterval(this.timer)
              return
            }
            this.percentage++
          }, 100)
        }
      }, (err, data) => {
        if (err || data.statusCode !== 200) { // 判断是否真正成功
          clearInterval(this.timer)
          this.isShowProgress = false
          this.percentage = 0
          this.$message.error('上传失败')
          this.fileList = this.fileList.filter(item => item.uid !== this.currentUid)
          return
        }
        let url
        this.fileList = this.fileList.map(item => {
          if (item.uid === this.currentUid) {
            item.url = ('https://' + data.Location)
            url = item.url
          }
          return item
        })
        this.$emit('onSuccess', this.fileList, url)
        setTimeout(() => {
          this.isShowProgress = false
        }, 500)
      })
    },
    onchange(_, fileList) {
      this.fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片上传之前校验
    beforeAvatarUpload(file) {
      /*   const maxSize = 1 * 1024 * 1024 // 1MB大小
      if (file.size >= maxSize) {
        this.$message.error('文件超过1MB')
        return false
      } else {
        return true
      }*/
      const type = ['image/jpeg', 'image/png', 'image/gif']
      const isImage = type.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.currentUid = file.uid

      return isImage && isLt2M
    }
  }
}
</script>

<style scoped lang='scss'>
.display {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}

.main {
  position: relative;
  height: 146px;
  overflow: hidden;
  ::v-deep .el-progress, .el-upload-list__item, .el-upload {
    position: absolute;
    left: 0;
    top: 0;
  }

}

</style>
